package com.tddx.activiti.business.common.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.tddx.activiti.business.sys.util.SysTuserUtil;
import com.tddx.activiti.common.Path;
import com.tddx.activiti.utils.FileUtils;

@Controller
@RequestMapping("fileupload")
public class FileUpload {
	
	static Logger log = Logger.getLogger(FileUpload.class);
	
	@RequestMapping("view")
	public String view(){
		return "file";
	}
	
	@RequestMapping("upload")
	@ResponseBody
	public String upload(@RequestParam(value = "file", required = false) MultipartFile file){
		
		log.info("。。。。上传开始。。。。。");
		OutputStream out = null;
		InputStream is = null;
		try {
			is = file.getInputStream();
			String fileName = file.getOriginalFilename();
			System.out.println("=========" + fileName);
			int result = saveFile(is, fileName);
			if(1==result){
				return "success";
			}
		} catch (IOException e) {
			log.error("。。。。获取文件流失败。。。。。");
			e.printStackTrace();
		}
		return "fail";
	}
	
	public static int saveFile(InputStream is, String fileName){
		int result = 0;
		OutputStream out = null;
		try {
			String toPath = Path.WEBROOT_PATH + SysTuserUtil.getCurrentUserName();
			File nf = FileUtils.createFile(toPath + File.separator + fileName);
			out = new FileOutputStream(nf);
			byte[] bs = new byte[1024];
			int len;
			while((len=is.read(bs))!=-1){
				out.write(bs, 0, len);
			}
			log.info("保存目录：" + toPath);
			result = 1;
		} catch (IOException e) {
			log.error("。。。。获取文件流失败。。。。。");
			e.printStackTrace();
		} finally{
			try {
				out.close();
				is.close();
			} catch (IOException e) {
				log.error("文件流关闭失败");
				e.printStackTrace();
			}
		}
		return result;
	}
	
}
